<template>
	<app-page>
		<wd-config-provider :theme="theme">
			<view class="container">
				<!-- 接单者 查询信息 -->
				<view class="query-info card " v-if="!isPosts">
					<!-- 查询信息内容 -->
					<view class="header">
						<view class="payment">
							<view class="payment-text">
								实付款：¥
							</view>
							<view class="payment-number">
								{{ orderInfo.money_total }}
							</view>
						</view>
						<view class="addr">
							{{ orderInfo.address_title }}
						</view>
					</view>
					<view class="content">
						<view class="content-item">
							<view class="content-item-label">协同类型：</view>
							<view class="content-item-value">{{ orderInfo.category_title }}</view>
						</view>
						<view class="content-item">
							<view class="content-item-label">协同状态：</view>
							<view class="content-item-value">{{ orderInfo.status_title }}
							</view>
						</view>
						<view class="content-item">
							<view class="content-item-label">
								发布时间
							</view>
							<view class="content-item-value">{{ orderInfo.create_time }}
							</view>
						</view>
						<view class="content-item">
							<view class="content-item-label">剩余有效期：</view>
							<view class="content-item-value">
								{{ validityPeriod.surplus }}天
							</view>
						</view>
					</view>
					<view class="money-info">
						<view class="title">
							费用明细
						</view>
						<view class="money-info-item">
							<view class="money-info-item-label">
								婚姻查询跑腿费
							</view>
							<view class="money-info-item-value">
								¥100
							</view>
							<view class="money-info-item-value">
								x1
							</view>
						</view>
						<view class="money-info-item">
							<view class="money-info-item-label">
								婚姻查询跑腿费
							</view>
							<view class="money-info-item-value">
								¥100
							</view>
							<view class="money-info-item-value">
								x1
							</view>
						</view>
					</view>
				</view>



				<!-- 发布者 查询信息 -->
				<view class="query-info card posts" v-if="isPosts">
					<!-- 查询信息内容 -->
					<view class="header">
						<view class="title">
							{{ orderInfo.anjian_name }}
						</view>
					</view>
					<view class="content">
						<view class="content-item">
							<view class="content-item-label">订单编号：</view>
							<view class="content-item-value">{{
								orderInfo.order_sn
							}}</view>
						</view>
						<view class="content-item">
							<view class="content-item-label">订单金额：</view>
							<view class="content-item-value">{{ orderInfo.money_total}}
							</view>
						</view>
						<view class="content-item">
							<view class="content-item-label">查询类型：
							</view>
							<view class="content-item-value">{{ orderInfo.category_title}}
							</view>
						</view>
						<view class="content-item">
							<view class="content-item-label">
								任务有效期({{ validityPeriod.surplus }}/{{ validityPeriod.expire_days }})</view>
							<view class="content-item-value">
								<wd-progress :percentage="validityPeriod.percentage" hide-text
									custom-class="wd-progress-custom-class-my-progress"
									:color="['#C91C1F', 'rgb(255, 153, 0)' ,'rgb(0,204, 0)' ]" />
							</view>
						</view>
					</view>
				</view>

				<!-- 发布者 任务进度 -->
				<view class="query-step card posts" v-if="isPosts">
					<!-- 查询备注内容 -->
					<view class="header">
						<view class="title">任务进度</view>
					</view>
					<view class="desc">
						<Step :stepList="stepList" :activ="stepActiv"></Step>
					</view>
				</view>
				<template v-if="status !== 998">
					<template v-for="(item,index) in fData">
						<view class="query-remark card" v-if="item.field_comment">
							<!-- 查询备注内容 -->
							<view class="title">发布者提供信息-{{item.field_comment}}</view>
							<view class="desc">
								<template
									v-if="item.field_type === 'Textarea' || item.field_type === 'Picker' || item.field_type === 'Input'||item.field_type === 'City'">
									{{ item.value }}
								</template>
								<template v-if="item.field_type === 'File'">
									<upload v-model="item.value" not-upload not-card padding=""></upload>
								</template>
							</view>
						</view>
					</template>
				</template>

				<template v-if="!isPosts || [50,40].includes(orderInfo.status)">
					<template v-for="(item,index) in jData">
						<view class="query-remark card" v-if="item.field_comment">
							<!-- 查询备注内容 -->
							<view class="title">接单人提供信息-{{item.field_comment}}</view>
							<view class="desc">
								<template
									v-if="item.field_type === 'Textarea' || item.field_type === 'Picker' || item.field_type === 'Input'||item.field_type === 'City'">
									{{ item.value }}
								</template>
								<template v-if="item.field_type === 'File'">
									<upload v-model="item.value" not-upload not-card padding=""></upload>
								</template>
							</view>
						</view>
					</template>
				</template>
				<!-- 接单者 任务提交 -->
				<wd-form ref="formRef" :model="formData" :rules="formRules" v-if="[998,3].includes(status) && !isPosts">
					<template v-for="(item,index) in formFields" :key="index">
						<view class="form-item" v-if="item.field_type !== 'Picker'">
							<wd-cell required :title="'请输入'+item.field_comment" vertical>
								<wd-textarea :prop="item.field_name" placeholderStyle="line-height:24px;"
									v-model="formData[item.field_name]" v-if="item.field_type === 'Textarea'"
									:placeholder="'请输入'+item.field_comment" />
								<wd-input v-if="item.field_type === 'Input'" :prop="item.field_name"
									v-model="formData[item.field_name]" :placeholder="'请输入'+item.field_comment" />
								<cityPicker v-if="item.field_type === 'City'" :prop="item.field_name"
									v-model="formData[item.field_name]" :placeholder="'请输入'+item.field_comment">
								</cityPicker>
								<upload :prop="item.field_name" v-model="formData[item.field_name]"
									v-if="item.field_type === 'File'">
								</upload>
							</wd-cell>
						</view>
						<wd-picker v-model="formData[item.field_name]" clearable :prop="item.field_name"
							custom-class="wd-picker-custom-class-fd-col square bg-transparent" :columns="item.params"
							:label="'请选择'+item.field_comment" v-if="item.field_type === 'Picker'" />
					</template>
				</wd-form>

				<view class="footer" v-if="isPosts">
					<view class="btns">
						<wd-button type="success" v-if="orderInfo.status_title == '已发布'" @click="doOrderPay"
							custom-class="wd-button-custom-class-my-cancel square wd-button-custom-class-w100">
							<text class="iconfont icon-sousuo"></text>
							去支付
						</wd-button>
						<wd-button type="success" v-if="orderInfo.status_title !== '待接单'" @click="doContactReceive"
							custom-class="wd-button-custom-class-my-cancel square wd-button-custom-class-w100">
							<text class="iconfont icon-sousuo"></text>
							联系接单人
						</wd-button>
						<wd-button v-if="orderInfo.status_title === '待确认'" @click="doMyCoopOrderOk" type="success"
							custom-class="wd-button-custom-class-my-success square wd-button-custom-class-w100">
							<text class="iconfont icon-xietong"></text>
							订单完成
						</wd-button>

					</view>
					<view class="after-sales" @click="doAfterSales"
						v-if="orderInfo.status_title !== '待接单' && orderInfo.status_title !== '已确认'">申请售后</view>
				</view>

				<view class="footer" v-if="!isPosts">
					<view class="btns">
						<wd-button type="success" @click="doContactRelease" v-if="orderInfo.is_back !== 1"
							custom-class="wd-button-custom-class-my-cancel square wd-button-custom-class-w100">
							<text class="iconfont icon-sousuo"></text>
							联系发布人
						</wd-button>
						<wd-button v-if="orderInfo.status_title === '待接单'" @click="receive" type="success"
							custom-class="wd-button-custom-class-my-success square wd-button-custom-class-w100">
							<text class="iconfont icon-xietong"></text>
							确认接单
						</wd-button>
						<wd-button v-if="orderInfo.status_title === '待完成' && status!== 998" type="success"
							@click="upload"
							custom-class="wd-button-custom-class-my-success square wd-button-custom-class-w100">
							<text class="iconfont icon-xietong"></text>
							上传资料
						</wd-button>
						<wd-button v-if="orderInfo.status_title === '待完成' && jData.length>0 && status!== 998"
							type="success" @click="submitOk"
							custom-class="wd-button-custom-class-my-success square wd-button-custom-class-w100">
							<text class="iconfont icon-xietong"></text>
							完成查询
						</wd-button>
						<wd-button v-if="status === 998" type="success" @click="submit"
							custom-class="wd-button-custom-class-my-success square wd-button-custom-class-w100">
							<text class="iconfont icon-xietong"></text>
							提交资料
						</wd-button>
					</view>
				</view>
			</view>
		</wd-config-provider>
	</app-page>

</template>

<script lang="ts">
	import { defineComponent, ref, computed, reactive } from 'vue';

	import useRouter from '@/hooks/useRouter.ts';
	import { onLoad } from '@dcloudio/uni-app';
	import { getQueryOrderInfo, doQueryReceiveOrder, getQueryMyReceiveSubmitFields, doSaveOrderInfo, doFinishOrder, doQueryComfirmFinish } from '@/api/query.ts';
	import Step from "@/components/step/step"
	import WxPay from "@/libs/WxPay"
	export default defineComponent({
		name: '',
		components: { Step },
		setup(props, ctx) {
			const router = useRouter();
			// 日间light、夜间dark主题
			const theme = ref('light');
			const isPosts : any = ref(null)
			const orderInfo = ref({});
			const status = ref(1);
			const isMeet = ref(true);
			// 表单 Ref
			const formRef = ref();
			const formFields = ref([]);
			const formRules = {
			};
			const formData = reactive({
			});
			const stepActiv = ref(0);
			const stepList = ref([
				{ title: '发布成功（等待接单）', status: 20 },
				{ title: '已接单（请耐心等待查询结果）', status: 30 },
				{ title: '已提交（请及时核对查询结果）', status: 40 },
				{ title: '已完成（该订单已结束）', status: 50 },
			])
			const receive = () => {
				uni.$wdToast.confirm("确认接单吗？", "提示").then((res : any) => {
					doQueryReceiveOrder({
						query_order_id: orderInfo.value['id']
					}).then((res) => {
						getOrderInfo();
					});
				});
			}
			const upload = () => {

				status.value = 998;
			}
			const submit = () => {
				formRef.value.validate().then(({ err, valid }) => { // 校验表单数据是否符合规则，符合则执行后续操作，否则不执行后续操作。
					if (!valid) {
						return false;
					}
					doSaveOrderInfo({
						query_order_id: orderInfo.value['id'], // 订单ID。
						...formData, // 表单数据。
					}).then(() => {
						getOrderInfo();
					});
				})
			}

			const submitOk = () => {
				uni.$wdToast.confirm("确认完成当前查询吗？", "提示").then((res : any) => {
					doFinishOrder({
						query_order_id: orderInfo.value['id']
					}).then((res) => {
						uni.$wdToast.show("提交成功 待发布者确认")
						getOrderInfo();
					});
				});
			}
			const doMyCoopOrderOk = () => {
				uni.$wdToast.confirm("确认当前查询已完成吗？", "提示").then((res : any) => {
					doQueryComfirmFinish({
						query_order_id: orderInfo.value['id']
					}).then((res) => {
						uni.$wdToast.show("确认成功")
						getOrderInfo();
					});
				});
			}
			const doAfterSales = () => {
				router.push({
					url: '/order/afterSaleService/afterSaleService',
					params: {
						id: orderInfo.value['id'], // 订单ID。
						type: "query"
					},
				})
			}
			const doContactRelease = () => {
				uni.$wdToast.confirm("点击确认后当前会拨打对方电话，请先确认对方是否方便接听", "提示").then((res) => {
					uni.makePhoneCall({
						phoneNumber: orderInfo.value.fdr_tel,
						success: () => {
						}
					});
				});
			}
			const doContactReceive = () => {
				uni.$wdToast.confirm("点击确认后当前会拨打对方电话，请先确认对方是否方便接听", "提示").then((res) => {
					uni.makePhoneCall({
						phoneNumber: orderInfo.value.fdr_tel,
						success: () => {
						}
					});
				});
			}
			const doOrderPay = (item) => {
				uni.$wdToast.confirm("支付后才任务才可以被人领取，确认支付吗？", "提示").then((res : any) => {
					const wxpay = new WxPay();
					wxpay.pay({
						orderId: item.id,
						type: 4,
						source: 1,
					}, {
						fail: () => {
							uni.$wdToast.show("取消支付")
							getOrderInfo();
						},
						getOrderCb: () => {
							uni.$wdToast.show("支付成功")
							getOrderInfo();
						}
					})
					// doQueryPayment({
					// 	query_order_id: item.id,
					// }).then((res) => {
					// 	uni.$wdToast.show("支付成功")
					// 	posts.reGetData();
					// })
				});
			}
			/**
			 * 计算两个日期之间的天数
			 *  date1  开始日期 yyyy-MM-dd
			 *  date2  结束日期 yyyy-MM-dd
			 *  如果日期相同 返回一天 开始日期大于结束日期，返回0
			 */
			function getDaysBetween(date1, date2) {
				var startDate = Date.parse(date1);
				var endDate = Date.parse(date2);
				if (startDate > endDate) {
					return 0;
				}
				if (startDate == endDate) {
					return 1;
				}
				var days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000);
				return days.toFixed(0);
			}

			const validityPeriod = computed(() => {
				let release = orderInfo.value.create_time;
				let expire_days = orderInfo.value.expire_days;
				let date = new Date();
				let between = getDaysBetween(release, date);
				let surplus = Number(expire_days) - Number(between) > 0 ? Number(expire_days) - Number(between) : 0; // 剩余天数。
				let percentage = Number(surplus) / expire_days * 100;
				return {
					expire_days,
					between,
					surplus,
					percentage,
				}
			})
			const fData = computed(() => {
				const temp = JSON.parse(JSON.stringify(orderInfo.value)); // 深拷贝，避免影响原始数据。
				const exd_fields_fdr = JSON.parse(temp['exd_fields_fdr'] || '[]'); // 转换为数组。
				let list = [];
				let keys = Object.keys(temp);
				if (exd_fields_fdr.length <= 0) {
					return list;
				}

				for (var i = 0; i < keys.length; i++) {
					let field = exd_fields_fdr.find((item : any) => item['field_name'] == keys[i])
					if (keys[i].indexOf("f_") !== -1 && temp[keys[i]] && keys[i] !== 'f_address_title' && field) {
						let d = {
							value: temp[keys[i]],
							...field
						}
						if (field.field_type === 'City' && temp.f_address_title) {
							d.value = temp?.f_address_title
						}

						list.push(d)
					}
				}
				return list;
			})
			const jData = computed(() => {
				const temp = JSON.parse(JSON.stringify(orderInfo.value)); // 深拷贝，避免影响原始数据。
				const exd_fields_jdr = JSON.parse(temp['exd_fields_jdr'] || '[]'); // 转换为数组。
				let list = [];
				let keys = Object.keys(temp);
				if (exd_fields_jdr.length <= 0) {
					return list;
				}
				for (var i = 0; i < keys.length; i++) {
					let field = exd_fields_jdr.find((item : any) => item['field_name'] == keys[i])
					if (keys[i].indexOf("f_") !== -1 && temp[keys[i]] && keys[i] !== 'f_address_title' && field) {
						let d = {
							value: temp[keys[i]],
							...field
						}
						if (field.field_type === 'City' && temp.f_address_title) {
							d.value = temp?.f_address_title
						}

						list.push(d)
					}
				}
				return list;
			})
			const getOrderInfo = (page_status ?) => {
				getQueryOrderInfo({
					query_order_id: orderInfo.value['id']
				}).then((res : any) => {
					orderInfo.value = res;
					stepActiv.value = stepList.value.findIndex((item : any) => item.status == res.status) // 设置步骤条的激活状态。
					if (page_status) {
						status.value = page_status
					} else {
						status.value = res.status
					}
					getQueryMyReceiveSubmitFields({
						category_id: orderInfo.value['category_id']
					}).then((res : any) => {
						formFields.value = res;
						for (let key in res) {
							formData[res[key].field_name] = '' // 初始化表单数据对象formData的属性值
							formRules[res[key].field_name] = [{ required: true, message: '请输入' + res[key].field_comment, trigger: 'blur' }] // 初始化表单验证规则对象formRules的属性值
						}
					});
					// console.log(validityPeriod);
				});
			}
			onLoad((param : any) => {
				if (param.isPosts === 'true') {
					isPosts.value = true; // 设置isPosts的值为true，表示是帖子查询。
				} else if (param.isPosts === 'false') {
					isPosts.value = false; // 设置isPosts的值为true，表示是帖子查询。
				}
				if (param.id) {
					orderInfo.value['id'] = param.id;
					if (param.status) {
						getOrderInfo(Number(param.status));
					} else {
						getOrderInfo();
					}
				} else {
					uni.$wdToast.show("没有订单信息")
					setTimeout(() => {
						router.back({
							delta: 1,
						})
					}, 1000); // 设置提示框显示时间，避免一直显示。
				}
			})
			return {
				theme,
				status,
				receive,
				submit,
				upload,
				isPosts,
				stepList,
				isMeet,
				orderInfo,
				fData,
				jData,
				formRef,
				formFields,
				formRules,
				formData,
				stepActiv,
				submitOk,
				doMyCoopOrderOk,
				doAfterSales,
				doContactRelease,
				doContactReceive,
				validityPeriod,
				doOrderPay,
			};
		}
	});
</script>
<!-- #ifdef MP-WEIXIN -->
<style lang="less">
	page {
		background-color: #f2f2f2;
	}
</style>
<!-- #endif -->
<style lang="less" scoped>
	page {
		background: #f2f2f2;
	}

	.container {
		padding: 24rpx;
		padding-bottom: 180rpx;

		.query-info {
			padding: 24rpx;
			width: calc(100% - 24rpx - 24rpx);

			.header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				font-family: PingFang;
				font-weight: 500;
				font-size: 28rpx;
				color: #999999;

				padding-bottom: 24rpx;
				position: relative;

				&::after {
					position: absolute;
					bottom: 0;
					content: " ";
					display: inline-block;
					width: 100%;
					height: 2rpx;
					background: #EEEEEE;
				}

				.payment {
					display: flex;
					align-items: center;




					.payment-number {
						color: #C91C1F;
						font-size: 50rpx;
						margin-left: 20rpx;
					}
				}
			}

			.content {
				padding: 24rpx 0 0;

				&-item {
					display: flex;
					align-items: center;
					justify-content: space-between;
					padding: 10rpx 0;
					font-family: PingFang;
					font-weight: 500;
					font-size: 28rpx;
					color: #999999;

					&-value {
						color: #000000;
						text-align: right;
						flex: 0 0 calc(100% - 260rpx);
					}

				}
			}

			.money-info {
				position: relative;
				padding-top: 24rpx;
				margin-top: 24rpx;
				// TODO 暂时隐藏
				display: none;

				&::before {
					position: absolute;
					top: 0;
					content: " ";
					display: inline-block;
					width: 100%;
					height: 2rpx;
					background: #EEEEEE;
				}

				.title {
					font-family: PingFang;
					font-weight: bold;
					font-size: 24rpx;
					color: #C91C1F;
				}

				&-item {
					margin-top: 12rpx;
					display: flex;
					justify-content: space-between;
					align-items: center;

					font-family: PingFang;
					font-weight: 400;
					font-size: 24rpx;
					color: #999999;

					&-value {
						color: #C91C1F;
					}
				}
			}
		}

		.posts {
			.header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				font-family: PingFang;
				font-weight: 500;
				font-size: 28rpx;
				color: #999999;

				padding-bottom: 24rpx;
				position: relative;

				&::after {
					position: absolute;
					bottom: 0;
					content: " ";
					display: inline-block;
					width: 100%;
					height: 2rpx;
					background: #EEEEEE;
				}

				.title {
					font-family: PingFang;
					font-weight: bold;
					font-size: 38rpx;
					color: #000000;
					padding: 0;
					text-align: center;

					&::after {
						display: none;
					}
				}
			}
		}

		.query-step {
			margin-top: 24rpx;
			padding: 24rpx;
			width: calc(100% - 24rpx - 24rpx);

			.desc {
				padding: 24rpx 0 0 0;
			}
		}

		.query-remark {
			margin-top: 24rpx;
			padding: 24rpx;
			width: calc(100% - 24rpx - 24rpx);

			.title {
				font-family: PingFang;
				font-weight: 500;
				font-size: 33rpx;
				color: #000000;
				position: relative;
				padding: 12rpx 0 36rpx;
				text-align: center;

				&::after {
					position: absolute;
					bottom: 0;
					left: 0;
					content: " ";
					display: inline-block;
					width: 100%;
					height: 2rpx;
					background: #EEEEEE;
				}
			}

			.desc {
				padding-top: 24rpx;
				font-family: PingFang;
				font-weight: 400;
				font-size: 24rpx;
				color: #999999;
				line-height: 40rpx;
			}
		}



		.card {
			position: relative;
			overflow: hidden;

			&::before {
				content: " ";
				display: inline-block;
				width: 100%;
				height: 8rpx;
				background: #C91C1F;
				position: absolute; // 设置为绝对定位，使其位于card元素下方
				top: 0; // 设置为card元素的下边界位置，使其紧贴底部
				left: 0; // 设置为card元素的左边界位置，使其紧贴左侧
			}
		}





		.form-item {
			// padding: 18rpx !important;
			margin-top: 18rpx;
			border-radius: 14rpx;
			overflow: hidden;

			:deep(.wd-textarea) {
				padding: 24rpx;
				border-radius: 14rpx;
			}

			:deep(.wd-input) {
				padding: 0 24rpx;
				border-radius: 14rpx;

				.wd-input__inner {
					height: 44px;
					line-height: 44px;
				}
			}

			:deep(.wd-cell) {
				background-color: transparent;
				padding-left: 0;

				.wd-cell__wrapper {
					padding-right: 0;
					padding: 0;
				}

				.wd-cell__right {
					margin-top: 20rpx;
				}

				.wd-cell__wrapper.is-vertical .wd-cell__value {
					max-width: 100%;
				}

				.wd-cell__body {
					// background-color: #FFF;
					border-radius: 14rpx;
				}
			}

		}

		.footer {
			position: fixed;
			width: calc(100% - 24rpx - 24rpx);
			padding: 24rpx 24rpx 0;
			bottom: 0;
			left: 0;
			// height: 180rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			background-color: #f2f2f2;

			.after-sales {
				font-family: PingFang;
				font-weight: bold;
				font-size: 22rpx;
				color: #000000;
				text-align: center;
				margin-bottom: 24rpx;
			}

			.btns {
				width: 100%;
				display: flex;

				justify-content: space-between;
				align-items: center;
				margin-bottom: 24rpx;

				:deep(.square) {
					flex: calc((100% - 27rpx) / 2);
					margin: 0;
					min-width: auto !important;

					.wd-button__text {
						display: flex;
						align-items: center; // 垂直居中
						justify-content: center; // 水平居中
						// flex-direction: column; // 子元素垂直排列
					}

					.icon-fabu {
						font-size: 40rpx;
						margin-top: 24rpx;
					}
				}

				:deep(.square+.square) {
					margin-left: 27rpx;
				}
			}
		}
	}
</style>